<template>
  <view class="other-profile-container">
    <!-- 顶部轮播图 -->
    <view class="banner-container">
      <!-- <swiper class="banner-swiper" circular indicator-dots :autoplay="true" interval="3000" duration="1000">
        <swiper-item v-for="(img, index) in imageList" :key="index">
          <image :src="globalConfig.site_url + img" mode="aspectFill" class="swiper-img" @error="handleImageError"></image>
        </swiper-item>
      </swiper> -->
    </view>

    <!-- 个人信息区域 -->
    <view class="profile-header">
      <u-avatar size="120" :src="userInfo.image ? (globalConfig.site_url + userInfo.image) : '/static/avatar.png'" @error="handleAvatarError" class="avatar"></u-avatar>
      <view class="user-info">
        <view class="nickname">{{ userInfo.nickname || '未知用户' }}</view>
        <view class="basic-info">{{ userInfo.age || '未知' }}岁 · {{ userInfo.zodiac || '未知星座' }}</view>
        <view class="tags" v-if="userInfo.tags && userInfo.tags.length">
          <text class="tag" v-for="tag in userInfo.tags" :key="tag">{{ tag }}</text>
        </view>
      </view>
      <u-icon name="more-dot" size="36" color="#fff" class="more-btn" @click="showActionSheet"></u-icon>
    </view>

    <!-- 加微信按钮 -->
    <u-button v-if="userInfo.wechat" type="primary" size="mini" class="wechat-btn" @click="copyWechat">{{ userInfo.wechat }}</u-button>

    <!-- 数据统计 -->
    <view class="stats-section">
      <view class="stat-item">
        <text class="num">{{ userInfo.follower_user_count || 0 }}</text>
        <text class="label">Ta的关注</text>
      </view>
      <view class="stat-item">
        <text class="num">{{ userInfo.visitors_count || 0 }}</text>
        <text class="label">访客</text>
      </view>
      <view class="stat-item">
        <text class="num">{{ userInfo.follower_count || 0 }}</text>
        <text class="label">关注Ta的</text>
      </view>
    </view>

    <!-- 动态区域 -->
    <view class="dynamic-section">
      <view class="dynamic-title">动态</view>
      <view v-if="posts.length === 0" class="dynamic-empty">暂无动态</view>
      <view v-else>
        <view v-for="item in posts" :key="item.id" class="dynamic-card">
          <view class="card-header" @click="goDetail(item)">
            <u-avatar :src="globalConfig.site_url + userInfo.image || '/static/avatar.png'" size="40" />
            <view class="user-info">
              <text class="nickname">{{ userInfo.nickname }}</text>
              <text class="time">{{ formatTime(item.createtime) }}</text>
            </view>
          </view>
          <view class="card-content">{{ item.info }}</view>
          <view v-if="item.images && item.images.length" class="card-images">
            <image v-for="(img, idx) in item.images" :key="idx" :src=" globalConfig.site_url + img" mode="aspectFill" class="card-img" />
          </view>
          <view class="card-footer">
            <text class="location">{{ item.area_name }}</text>
            <!-- <view class="actions">
              <u-icon name="thumb-up" size="24" :color="item.liked ? '#ff4d4f' : '#8e24aa'" @click.stop="handleLike(item)"></u-icon>
              <text>{{ item.likes_count }}</text>
              <u-icon name="chat" size="24" color="#8e24aa" style="margin-left: 24rpx;" @click="goDetail(item)"></u-icon>
              <text>{{ item.comments_count }}</text>
            </view> -->
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions" v-if="userId != getUserInfo.id">
      <u-button type="primary" shape="circle" class="follow-btn" @click="handleFollow">{{ isFollowing == 1 ? '取消关注' : '+ 关注' }}</u-button>
      <u-button  type="success" shape="circle" class="chat-btn" @click="goToChat">搭一下</u-button>
    </view>

    <!-- 举报操作菜单 -->
    <u-action-sheet v-model="showActionSheet" :list="actionSheetList" @click="handleActionClick"></u-action-sheet>
  </view>
</template>

<script>
import { getUserProfile, followUser, reportUser } from '@/api/user.js';
import { createChat } from '@/api/chat.js';
import { mapGetters, mapState } from 'vuex';

export default {
  name: 'OtherProfile',
  data() {
    return {
      userId: '',
      userInfo: {},
      posts: [],
      imageList: [],

      isFollowing: 0,
      showActionSheet: false,
      actionSheetList: [{
        text: '举报用户',
        color: '#ff4d4f'
      }]
    };
  },
 computed: {
    ...mapGetters(['getUserInfo']),
      // 使用mapState直接访问state
    ...mapState({
      globalConfig: state => state.config,
      userLocation: state => state.location,
    })
  },
  onLoad(options) {
      this.userId = options.id;
      console.log(this.userId);
      
      this.fetchUserProfile();
    },
  methods: {
    // 获取用户资料
    async fetchUserProfile() {
      try {
        this.loading = true;
        const res = await getUserProfile({ user_id: this.userId });
        console.log(res, '获取用户资料');
        
        if (res.data.code === 1) {
          this.userInfo = res.data.data;
          this.isFollowing = res.data.data.is_follow;
          console.log(res.data.data, 'this.isFollowing');
          // 处理轮播图图片
          this.imageList = this.userInfo.images ? this.userInfo.images.split(',').filter(img => img) : [];
        if (this.imageList.length === 0) {
          this.imageList = ['/static/default-banner.png'];
        }
        // 直接从用户信息获取动态列表
        this.posts = this.userInfo.posts_list ? this.userInfo.posts_list.map(item => ({
          ...item,
          images: item.images ? item.images.split(',').filter(img => img) : []
        })) : [];
        } else {
          uni.showToast({ title: '获取用户资料失败', icon: 'none' });
        }
      } catch (error) {
        console.log('获取用户资料失败:', error);
        
        uni.showToast({ title: '网络错误', error});
      } finally {
        this.loading = false;
      }
    },
    // 格式化时间
    formatTime(ts) {
      if (!ts) return '';
      const date = new Date(ts * 1000);
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    },
    // 关注用户
    async handleFollow() {
      try {
        const res = await followUser({type: this.isFollowing == 1 ? 2 : 1, user_id: this.userId });
        if (res.data.code === 1) {
          this.isFollowing = this.isFollowing == 1 ? 2 : 1;
          uni.showToast({ title: this.isFollowing == 1 ? '关注成功' : '取消关注成功' });
           this.fetchUserProfile();
        } else {
          uni.showToast({ title: res.msg || '关注失败', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '操作失败', icon: 'none' });
      }
    }, 
    async goToChat() {
      uni.showLoading({ title: '创建聊天中...' });
      try {
        // 使用封装的API方法创建单聊
        const res = await createChat({ user_id: this.userId });
        
        if (res.data.code === 1) {
          const chatId = res.data.data.chat_id;
          // 携带chatId跳转到聊天页面
          uni.navigateTo({ url: `/pages/chat/detail?teamId=${chatId}` });
        } else {
          uni.showToast({ title: res.data.msg || '创建聊天失败', icon: 'none' });
        }
      } catch (error) {
        console.error('创建聊天失败:', error);
        uni.showToast({ title: error.message || '网络错误', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },
    // 跳转到动态详情
    goDetail(item) {
      uni.navigateTo({ url: `/pages/dynamic/comment?id=${item.id}` });
    },
    // 复制微信号
    copyWechat() {
      uni.setClipboardData({
        data: this.userInfo.wechat,
        success: () => {
          uni.showToast({ title: '微信号已复制' });
        }
      });
    },

    // 处理举报
    async handleActionClick(index) {
      if (index === 0) {
        // 举报用户
        const confirm = await uni.showModal({
          title: '举报',
          content: '确定要举报该用户吗？',
          confirmText: '确定',
          cancelText: '取消'
        });
        if (confirm.confirm) {
          try {
            const res = await reportUser(this.userId);
            if (res.code === 1) {
              uni.showToast({ title: '举报成功' });
            } else {
              uni.showToast({ title: res.msg || '举报失败', icon: 'none' });
            }
          } catch (error) {
            uni.showToast({ title: '举报失败', icon: 'none' });
          }
        }
      }
      this.showActionSheet = false;
    },

    // 图片加载失败处理
    handleAvatarError(e) {
      e.target.src = '/static/avatar.png';
    },
    handleImageError(e) {
      e.target.src = '/static/default-banner.png';
    }
  },
};
</script>

<style scoped lang="less">
.other-profile-container {
  min-height: 100vh;
  background: #1a1a1a;
  color: #fff;
  padding-bottom: 120rpx;
}

.banner-container {
  width: 100%;
  height: 280rpx;
  position: relative;
}

.banner-swiper {
  width: 100%;
  height: 100%;
}

.swiper-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.profile-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 32rpx;
  margin-top: -60rpx;
  position: relative;
}

.avatar {
  border: 4rpx solid #1a1a1a;
  margin-bottom: 20rpx;
}

.user-info {
  text-align: center;
  margin-bottom: 20rpx;
}

.nickname {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.basic-info {
  font-size: 28rpx;
  color: #ccc;
  margin-bottom: 12rpx;
}

.tags {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-top: 10rpx;
}

.tag {
  background: #333;
  color: #fff;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.more-btn {
  position: absolute;
  right: 32rpx;
  top: 20rpx;
}

.wechat-btn {
  position: absolute;
  top: 20rpx;
  right: 80rpx;
  background: #07c160;
  color: #fff;
}

.stats-section {
  display: flex;
  justify-content: space-around;
  margin: 32rpx 0;
  background: #2d2d2d;
  padding: 20rpx 0;
  border-radius: 16rpx;
}

.stat-item {
  text-align: center;
}

.num {
  display: block;
  font-size: 32rpx;
  color: #fff;
  font-weight: bold;
}

.label {
  font-size: 24rpx;
  color: #ccc;
}

.dynamic-section {
  background: #1a1a1a;
  border-radius: 16rpx;
  margin: 0 32rpx 32rpx;
  padding: 0;
  text-align: center;
  position: relative;
}

.dynamic-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
  padding: 24rpx 32rpx;
  text-align: left;
  border-bottom: 1rpx solid #333;
}

.dynamic-empty,
.loading-text,
.finished-text {
  color: #666;
  font-size: 28rpx;
  padding: 40rpx 0;
}

.dynamic-card {
  background: #2d2d2d;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.4);
  margin: 0 32rpx 24rpx;
  padding: 32rpx;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.card-content {
  font-size: 28rpx;
  color: #fff;
  margin-bottom: 16rpx;
  text-align: left;
}

.card-images {
  display: flex;
  gap: 12rpx;
  margin-bottom: 16rpx;
  flex-wrap: wrap;
}

.card-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  object-fit: cover;
}

.card-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 24rpx;
  color: #aaa;
}

.actions {
  display: flex;
  align-items: center;
  gap: 8rpx;
  color: #8e24aa;
}

.bottom-actions {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 32rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #1a1a1a;
  border-top: 1rpx solid #333;
}

.follow-btn,
.chat-btn {
  width: 280rpx;
  height: 80rpx;
  font-size: 32rpx;
  color: #fff;
}

.follow-btn {
  // background: #8e24aa;//
  color: #fff;
}

.chat-btn {
  // background: #ff7a45;
}
</style>